﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Media;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using Microsoft.WindowsAPICodePack.Shell.PropertySystem;
using Microsoft.WindowsAPICodePack.Taskbar;
using MiniPomodoro.Properties;

namespace MiniPomodoro
{
    //TODO 可以设置番茄时间 设置休息时间
    //TODO 可以切换不同的背景音效
    //TODO 可以用快捷键增大音量 减小音量 关闭音量
    public partial class MainForm : Form
    {
        private decimal WorkMinutes = 25M; //25; // 一个番茄的时间
        private decimal ShortRestMinutes = 5M; //5; // 休息时间
        private DateTime _startTime;
        //private string songpath= "D:\\CloudMusic\\a\\333.mp3";
        private string tickpath = AppDomain.CurrentDomain.BaseDirectory + "MP3\\ticking.mp3";
        string songpath = AppDomain.CurrentDomain.BaseDirectory + "Music";
        private string playpath;
        private int playvolume = 0;
        private PomodoState _currentState;
        private bool tickingflag = true;
        public MainForm()
        {
            InitializeComponent();
        }

        public const int MM_MCINOTIFY = 0x3B9;  //这是声明 播完音乐 mciSendString（）向系统发送的指令
        protected override void DefWndProc(ref Message m)
        {
            base.DefWndProc(ref m);

            //if (m.Msg == MM_MCINOTIFY) //判断指令是不是MM_MCINOTIFY

            ////当歌曲播完 mciSendString（）向系统发送的MM_MCINOTIFY指令
            //{
            //    PlaySong(songpath);//播完就自动播放这个。。。
            //}
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            Mci.volume = playvolume = int.Parse(ConfigurationManager.AppSettings.Get("Playvolume"));
            if (playvolume != 0)
            {
                contextMenuStrip1.Items[2].Text = "关闭工作背景音效";
            }
            Mci.PlayRepeat(tickpath);  // when complete callback to DefWndProc 
            //设置鼠标放在托盘图标上面的文字 
            var path = ConfigurationManager.AppSettings.Get("Filename");
            GetMp3File(string.IsNullOrEmpty(path) ? songpath : path);
            this.notifyIcon1.Text = "番茄";
            // 打开程序自动开始一个新的工作番茄
            StartWorkPomodo();
            timer1.Start();
        }

        /// <summary>
        /// 开始一个新的工作番茄
        /// </summary>
        private void StartWorkPomodo()
        {
            _startTime = DateTime.Now;
            _currentState = PomodoState.Working;
        }

        /// <summary>
        /// 开始一个新的休息番茄
        /// </summary>
        private void StartRestPomodo()
        {
            _startTime = DateTime.Now;
            _currentState = PomodoState.Resting;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            // 检查是否需要切换状态
            var elapsedMinutes = GetElapsedMinutes(); // 已经消耗的分钟数
            if (_currentState == PomodoState.Working)
            {
                if (elapsedMinutes >= WorkMinutes)
                {
                    StartRestPomodo();
                }
            }
            else if (_currentState == PomodoState.Resting)
            {
                if (elapsedMinutes >= ShortRestMinutes)
                {
                    timer1.Stop();
                    MessageBox.Show("休息时间结束，即将开始新的番茄！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    timer1.Start();
                    Mci.PlayRepeat(tickpath);
                    tickingflag = true;
                    StartWorkPomodo();
                }
            }
            // 显示效果
            elapsedMinutes = GetElapsedMinutes(); // 已经消耗的分钟数
            if (_currentState == PomodoState.Working)
            {
                // 显示进度
                int progress = 100 - Convert.ToInt32(elapsedMinutes / WorkMinutes * 100);
                TaskBar.SetProgressValue(progress, TaskbarProgressBarState.Normal);

                // 显示剩余分钟数
                int leftMinitues = Convert.ToInt32(WorkMinutes - Math.Floor(elapsedMinutes));
                #region MyRegion
                switch (leftMinitues)
                {
                    case 1:
                        TaskBar.SetTaskBarIcon(Resources.W1);
                        break;
                    case 2:
                        TaskBar.SetTaskBarIcon(Resources.W2);
                        break;
                    case 3:
                        TaskBar.SetTaskBarIcon(Resources.W3);
                        break;
                    case 4:
                        TaskBar.SetTaskBarIcon(Resources.W4);
                        break;
                    case 5:
                        TaskBar.SetTaskBarIcon(Resources.W5);
                        break;
                    case 6:
                        TaskBar.SetTaskBarIcon(Resources.W6);
                        break;
                    case 7:
                        TaskBar.SetTaskBarIcon(Resources.W7);
                        break;
                    case 8:
                        TaskBar.SetTaskBarIcon(Resources.W8);
                        break;
                    case 9:
                        TaskBar.SetTaskBarIcon(Resources.W9);
                        break;
                    case 10:
                        TaskBar.SetTaskBarIcon(Resources.W10);
                        break;
                    case 11:
                        TaskBar.SetTaskBarIcon(Resources.W11);
                        break;
                    case 12:
                        TaskBar.SetTaskBarIcon(Resources.W12);
                        break;
                    case 13:
                        TaskBar.SetTaskBarIcon(Resources.W13);
                        break;
                    case 14:
                        TaskBar.SetTaskBarIcon(Resources.W14);
                        break;
                    case 15:
                        TaskBar.SetTaskBarIcon(Resources.W15);
                        break;
                    case 16:
                        TaskBar.SetTaskBarIcon(Resources.W16);
                        break;
                    case 17:
                        TaskBar.SetTaskBarIcon(Resources.W17);
                        break;
                    case 18:
                        TaskBar.SetTaskBarIcon(Resources.W18);
                        break;
                    case 19:
                        TaskBar.SetTaskBarIcon(Resources.W19);
                        break;
                    case 20:
                        TaskBar.SetTaskBarIcon(Resources.W20);
                        break;
                    case 21:
                        TaskBar.SetTaskBarIcon(Resources.W21);
                        break;
                    case 22:
                        TaskBar.SetTaskBarIcon(Resources.W22);
                        break;
                    case 23:
                        TaskBar.SetTaskBarIcon(Resources.W23);
                        break;
                    case 24:
                        TaskBar.SetTaskBarIcon(Resources.W24);
                        break;
                    case 25:
                        TaskBar.SetTaskBarIcon(Resources.W25);
                        break;
                    default:
                        TaskBar.SetTaskBarIcon(Resources.W1);
                        break;
                }
                #endregion
            }
            else if (_currentState == PomodoState.Resting)
            {
                int progress = 100 - Convert.ToInt32(elapsedMinutes / ShortRestMinutes * 100);
                int currentSecond = DateTime.Now.Second;
                if (currentSecond % 2 == 0)
                {
                    if (mp3FilesList.Any() && tickingflag)
                    {
                        var index = int.Parse(ConfigurationManager.AppSettings.Get("PlayIndex"));
                        mp3FilesList = mp3FilesList.OrderBy(x => x).ToList();
                        tickingflag = false;
                        playpath = mp3FilesList[index];
                        var result = true;
                        while (Mci.PlaySong(playpath, this.Handle) != 0)//如果失败进入下一首
                        {
                            result = false;
                            index++;
                            playpath = mp3FilesList[index];
                        }
                        if (result)
                        { index++; }
                        if (index == mp3FilesList.Count - 1)
                        {
                            index = 0;
                        }
                        SetConfig("PlayIndex", index.ToString());
                    }
                    // 显示剩余分钟数
                    TaskBar.SetTaskBarIcon(Resources.R5);
                    // 显示进度
                    TaskBar.SetProgressValue(progress, TaskbarProgressBarState.Paused);
                }
                else
                {
                    // 进度闪烁
                    TaskBar.ClearProgressValue();
                }
            }
        }

        /// <summary>
        /// 返回已经消耗了多少分钟
        /// </summary>
        /// <returns></returns>
        private decimal GetElapsedMinutes()
        {
            return Convert.ToDecimal((DateTime.Now - _startTime).TotalMinutes);
        }

        private void Appset(string filepath)
        {
            //Create the object
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            //make changes
            config.AppSettings.Settings["Filename"].Value = filepath;

            //save to apply changes
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");
        }

        private void SetConfig(string key, string value)
        {
            //Create the object
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            //make changes
            config.AppSettings.Settings[key].Value = value;
            //save to apply changes
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");
        }

        List<string> mp3FilesList = new List<string>();
        private void GetMp3File(string filepath)
        {
            var folder = new DirectoryInfo(filepath);
            if (!folder.Exists)
            {
                folder = new DirectoryInfo(songpath);
            }
            foreach (var file in folder.GetFiles("*.mp3"))
            {
                mp3FilesList.Add(file.FullName);
            }
        }

        private void contextMenuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            var clickitem = e.ClickedItem;
            if (clickitem.Text == "设置文件夹")
            {
                var folder = new FolderBrowserDialog { Description = "选择所有文件存放目录" };
                if (folder.ShowDialog() == DialogResult.OK)
                {
                    var sPath = folder.SelectedPath;
                    Appset(sPath);
                    GetMp3File(sPath);
                }
            }
            else if (clickitem.Text == "播放工作背景音效")
            {
                SetConfig("Playvolume", "1000");
                Mci.volume = playvolume = 1000;
                Mci.SetVolume();
                clickitem.Text = "关闭工作背景音效";
            }
            else if (clickitem.Text == "关闭工作背景音效")
            {
                SetConfig("Playvolume", "0");
                Mci.volume = playvolume = 0;
                Mci.SetVolume();
                clickitem.Text = "播放工作背景音效";
            }
            else if (clickitem.Text == "退出")
            {
                Application.Exit();
            }
        }
    }

    public enum PomodoState
    {
        /// <summary>
        /// 工作中
        /// </summary>
        Working = 0,
        /// <summary>
        /// 休息中
        /// </summary>
        Resting = 1
    }
}
